<template>
  <div>
    <Modal v-model="modalSwitch" width="1000">
      <p slot="header" style="text-align:center">
        <span>选择地址</span>
      </p>
      <div class="disFlex vertical" v-if="cityData && modalSwitch">
        <div class="disFlex Flex-middle">
          <Select
            class="province"
            size="large"
            v-model="mapMessage.province"
            @on-change="provinceChangeFn"
          >
            <Option
              v-for="(item,index) in cityData"
              :value="item.name"
              :key="item.name"
            >{{item.name}}</Option>
          </Select>
          <Select class="city" size="large" v-model="mapMessage.city" @on-change="cityChangeFn">
            <Option
              v-for="(item,index) in findProvinceFn(mapMessage.province)"
              :value="item.name"
              :key="item.name"
            >{{item.name}}</Option>
          </Select>
          <Select class="area" size="large" v-model="mapMessage.area" @on-change="areaChangeFn">
            <Option
              v-for="(item,index) in findCityFn(mapMessage.province,mapMessage.city)"
              :value="item.name"
              :key="item.name"
            >{{item.name}}</Option>
          </Select>
          <Input
            class="adress-input"
            v-model="mapMessage.searchVal"
            size="large"
            placeholder="请输入地址"
            @on-enter="searchFn"
          />
          <Button class="adress-btn" size="large" type="primary" @click="searchFn">搜索</Button>
        </div>
        <span class="now-address">当前位置: {{nowAddress}}</span>
        <div id="map" style></div>
      </div>
      <div class="disFlex Flex-center" slot="footer">
        <Button type="primary" size="large" @click="commitMapFn">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import cityData from '@/common/js/city.js'
export default {
  name: 'wxmap',
  data () {
    return {
      modalSwitch: false,
      cityData: null,// 所有城市数据
      geocoder: null,// 地图搜索使用
      // 地图信息
      mapMessage: {
        province: '北京',
        city: '北京市',
        area: '',
        searchVal: '',
        numPosition: {
          lat: 39.92855,
          lng: 116.41637,
        },
      },
      map: null,// 地图信息
      marker: null,// 地图水滴标志
      info: null,// 地图信息窗口
      isSearch: true, //是否切换搜索过
      changeIndex: -1,// 修改的下标
      nowAddress: ''// 当前地址
    }
  },
  mounted () {
    this.cityData = [...cityData]// 所有城市数据
  },
  methods: {
    // 打开地图
    openFn (_obj, _index) {
      console.log(_obj)
      //不存在数据，赋值默认数据
      if (!_obj.numPosition) {
        _obj = JSON.parse(JSON.stringify(this.mapMessage))
      }

      if (_index == 'selectCity') {
        // 检查省份是否正确 
        let off = true

        console.log(_obj)
        let provinceOff = this.cityData.findIndex((item, index) => {
          return item.name == _obj.province
        })

        off = provinceOff == -1 ? false : true

        if (!off) {
          this.$Message.info('请选择正确的省份');
          return false
        }

        this.isSearch = false
      }

      this.changeIndex = _index
      this.modalSwitch = true
      if (Object.keys(_obj).length != 0 && _obj.province != '' && (_obj.numPosition.lat != 0 || _obj.numPosition.lng != 0)) {
        // 拷贝传入的地理数据
        this.mapMessage = JSON.parse(JSON.stringify(_obj))
      }

      // 把这个模板挂在到window下面/加载地图api
      this.$nextTick(() => {
        this.cteatScriptFn()
      })
    },

    // 创建地图script
    cteatScriptFn () {
      // window['shopEdit'] = this 

      let _this = this

      window.init = function (argument) {
        _this.initMapFn(window.qq)
      }

      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "https://map.qq.com/api/js?v=2.exp&key=JLJBZ-T5ZL2-BELUZ-C6DNP-HU4M5-SJBAG&callback=init";
      document.body.appendChild(script);
    },

    // 初始化地图
    initMapFn (_fn) {
      let _this = this

      let geocoder, map, marker = null;

      // 设置中心点
      let center = new qq.maps.LatLng(39.98174, 116.30631);

      // 创建地图
      map = new qq.maps.Map(document.getElementById('map'), {
        center: center,
        zoom: 15
      });

      //创建一个Marker(水滴标志)
      marker = new qq.maps.Marker({
        //设置Marker的位置坐标
        position: center,
        //设置显示Marker的地图
        map: map
      });

      // 设置可拖动
      marker.setDraggable(true);

      // 监听拖拽后的回调
      qq.maps.event.addListener(marker, 'dragend', function () {
        _this.setNumPositionFn(marker.getPosition())
        let coord = new qq.maps.LatLng(_this.mapMessage.numPosition.lat, _this.mapMessage.numPosition.lng);
        _this.geocoder.getAddress(coord)
      });

      // 地图实例
      _this.map = map
      // 地图位置图标
      _this.marker = marker

      //调用地址解析类
      geocoder = new qq.maps.Geocoder({
        complete: function (result) {
          _this.map.setCenter(result.detail.location);
          _this.marker.setMap(_this.map)
          _this.marker.setPosition(result.detail.location)
          _this.setNumPositionFn(result.detail.location)
          let coord = new qq.maps.LatLng(_this.mapMessage.numPosition.lat, _this.mapMessage.numPosition.lng);
          _this.nowAddress = result.detail.address
        }
      });

      // 地址解析类
      _this.geocoder = geocoder

      // 初始化有数据(检查是否有传入数据)
      if (Object.keys(_this.mapMessage).length != 0) {
        _this.init(_this.mapMessage)
      }
    },

    // 省区改变
    provinceChangeFn (_province) {
      let _provinceIndex

      // 查找省对应的下标
      this.cityData.forEach((item, index) => {
        if (item.name == _province) {
          _provinceIndex = index
        }
      })

      this.mapMessage.province = _province
      this.mapMessage.city = this.cityData[_provinceIndex].sub[0].name
      this.mapMessage.area = this.cityData[_provinceIndex].sub[0].sub[0].name
      this.isSearch = false
    },

    // 城市改变
    cityChangeFn (_city) {
      this.mapMessage.city = _city

      // 查找省下标
      let _provinceIndex
      this.cityData.forEach((item, index) => {
        if (item.name == this.mapMessage.province) {
          _provinceIndex = index
        }
      })

      let _cityIndex
      // 查找市的下标
      this.cityData[_provinceIndex].sub.forEach((item, index) => {
        if (item.name == _city) {
          _cityIndex = index
        }
      })
      this.mapMessage.area = this.cityData[_provinceIndex].sub[_cityIndex].sub ? this.cityData[_provinceIndex].sub[_cityIndex].sub[0].name : ''
      this.isSearch = false
    },

    // 区域改变
    areaChangeFn (_area) {
      this.mapMessage.area = _area
      this.isSearch = false
    },

    // 搜索
    searchFn () {
      this.isSearch = true

      let searchAddress = [this.mapMessage.province, this.mapMessage.city, this.mapMessage.area, this.mapMessage.searchVal].join(',')

      // 正则去掉最后一位为“,”
      searchAddress = searchAddress.replace(/,$/, '')

      this.geocoder.getLocation(searchAddress);
    },

    // 初始化
    init (_obj) {
      // 判断是否有经纬度数据
      if (_obj.numPosition.lat != 0 && _obj.numPosition.lng != 0) {
        this.map.setCenter(new qq.maps.LatLng(this.mapMessage.numPosition.lat, this.mapMessage.numPosition.lng))
        this.marker.setPosition(new qq.maps.LatLng(this.mapMessage.numPosition.lat, this.mapMessage.numPosition.lng))
        let coord = new qq.maps.LatLng(this.mapMessage.numPosition.lat, this.mapMessage.numPosition.lng);
        this.geocoder.getAddress(coord)
      } else {
        let searchAddress = [this.mapMessage.province, this.mapMessage.city, this.mapMessage.area, this.mapMessage.searchVal].join(',')

        // 正则去掉最后一位为“,”
        searchAddress = searchAddress.replace(/,$/, '')
        this.geocoder.getLocation(searchAddress);
      }
    },

    // 设置经纬度
    setNumPositionFn (_obj) {
      this.mapMessage.numPosition.lat = _obj.lat
      this.mapMessage.numPosition.lng = _obj.lng
    },

    // 确定返回数组
    commitMapFn () {
      if (!this.isSearch) {
        this.$Message.warning('请搜索确认下是否是准确位置');
        return false
      }
      // console.log(this.mapMessage)
      this.$emit('commitMapFn', JSON.parse(JSON.stringify(this.mapMessage)), this.changeIndex)
      this.modalSwitch = false
    },

    // 根据省查找对应的城市
    findProvinceFn (_province) {
      return this.cityData.filter((item, index) => {
        if (item.name == _province) {
          return item
        }
      })[0].sub
    },

    // 根据市查对应的区
    findCityFn (_province, _city) {
      let _provinceIndex
      this.cityData.forEach((item, index) => {
        if (item.name == _province) {
          _provinceIndex = index
        }
      })

      return this.cityData[_provinceIndex].sub.filter((item, index) => {
        if (item.name == _city) {
          return item
        }
      })[0].sub
    }
  },
}
</script>

<style scoped lang="less">
.province {
  width: 150px;
}

.city {
  width: 150px;
  margin-left: 10px;
}

.area {
  width: 150px;
  margin-left: 10px;
}

.adress-input {
  margin-left: 10px;
}

.adress-btn {
  margin-left: 10px;
}

#map {
  width: 100%;
  height: 550px;
  margin-top: 15px;
}

.now-address {
  margin-top: 15px;
}
</style>